import storage from 'store'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Qs from 'qs'
import antDesign from 'ant-design-vue'

// eslint-disable-next-line no-undef
let baseURL

if (process.env.NODE_ENV === 'development') {
  // 开发环境
  baseURL = process.env.VUE_APP_API_BASE_URL
} else {
  // 编译环境
  if (process.env.type === 'test') {
    // 测试环境
    // eslint-disable-next-line no-undef,no-self-assign
    // 在这里使用配置文件中的域名
  } else {
    // 正式环境
    // eslint-disable-next-line no-undef,no-self-assign
    // 在这里使用配置文件中的域名
  }
  baseURL = process.env.VUE_APP_API_BASE_URL
}
// 创建 axios 实例
const service = axios.create({
  baseURL: baseURL // api base_url
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  antDesign.Message.error('网络请求失败……')
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if (config.method === 'post') {
    config.data = Qs.stringify({ ...config.data })
  } else {
    config.params = { ...config.params }
  }
  // if (config.timeOut !== undefined && config.timeOut != null) {
  //   service.timeout = config.timeOut
  // } else {
  //   service.timeout = 1000
  // }
  if (config.responseType) {
    service.responseType = config.responseType
  } else {
    config.headers.Accept = 'application/json'
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  if (response.data.code === '0000') {
    return response.data
  } else if (response.data.code === '8888') {
    antDesign.Message.error('该账号暂未获取操作授权，请联系管理员或重新登录')
  } else if (response.data.code === '9999') {
    antDesign.Message.destroy()
    antDesign.Modal.error({
      title: '不好意思，出问题了！',
      content: response.data.content
    })
    // antDesign.Message.error(response.data.content)
    return Promise.reject(response.data.content)
  } else {
    if (service.responseType) {
      const data = response.data
      if (typeof (data) === 'object' &&
        Object.prototype.toString.call(data).toLowerCase() === '[object object]' && !data.length) {
        antDesign.Message.error(response.data.content)
        return Promise.reject(response.data.content)
      } else {
        // if (typeof data === 'dd') {
        //   antDesign.Message.error(response.data.content)
        //   return Promise.reject(response.data.content)
        // }
        // 有可能下载失败，返回{code: '500'},但responseType: 'blob'会把data强制转为blob，导致下载undefined.excel
        // 解决：将已转为blob类型的data转回json格式，判断是否下载成功
        const r = new FileReader()
        r.onload = function () {
          // 如果JSON.parse(this.result)不报错，说明this.result是json字符串，是下载报错情况的返回值，弹框提示
          // 如果JSON.parse(this.result)报错，说明下载成功，进入catch
          try {
            const resData = JSON.parse(this.result) // this.result为FileReader获取blob数据转换为json后的数据，即后台返回的原始数据
            if (resData && resData.code) {
              if (resData.code === '500') {
                antDesign.Message.error('下载失败')
                return Promise.reject('下载失败')
              } else if (resData.code === '9999') {
                antDesign.Message.error(resData.content)
                return Promise.reject(resData.content)
              }
            }
          } catch (err) {
            let fileName = response.headers['content-disposition']
            // 获取文件名
            if (fileName && fileName.length >= 2) {
              fileName = fileName.split('=')[1]
            }
            fileName = decodeURIComponent(fileName)
            // 兼容ie11
            if (window.navigator.msSaveOrOpenBlob) {
              try {
                const blobObject = new Blob([data])
                window.navigator.msSaveOrOpenBlob(blobObject, fileName)
              } catch (e) {
                console.log(e)
              }
              return
            }
            const url = window.URL.createObjectURL(new Blob([data]))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            // eslint-disable-next-line no-undef
          }
        }
        r.readAsText(data) // FileReader的API
      }
    } else {
      const closeMe = store.getters.getCloseMessageList()
      if (closeMe.length > 0) {
        for (const closeMeKey in closeMe) {
          setTimeout(closeMe[closeMeKey], 1000)
        }
      }
      if (response.data.content !== undefined && response.data.content !== '') {
        // antDesign.Message.error(response.data.content)
        antDesign.Notification.error({
          message: '系统提示',
          description:
            response.data.content,
          duration: 8
        })
      }
      return Promise.reject(response.data.content)
    }
  }
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
